﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using audio.Helper;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;

namespace audio.Play
{
    /// <summary>
    /// 音频播放
    /// </summary>
    public class AudioPlay
    {
        readonly ILog _log = new LogInfo("log4net.config", "");

        private BufferedWaveProvider _bufferedWaveProvider;
        private IWavePlayer _waveOut;
        readonly byte[] _buffer = new byte[16384 * 4];
        IMp3FrameDecompressor _decompressor;

        public void StreamMp3File(Mp3Frame frame)
        {
            try
            {


                if (IsBufferNearlyFull)
                {
                    Thread.Sleep(500);
                }


                if (_decompressor == null)
                {
                    //创建描述
                    WaveFormat waveFormat = new Mp3WaveFormat(
                            frame.SampleRate,
                            frame.ChannelMode == ChannelMode.Mono ? 1 : 2,
                            frame.FrameLength,
                            frame.BitRate
                        );
                    //(int sampleRate, int channels, int blockSize, int bitRate)
                    //BitRate: 192000
                    //BitRateIndex: 6
                    //ChannelExtension: 1
                    //ChannelMode: JointStereo
                    //Copyright: false
                    //CrcPresent: true
                    //FileOffset: 21
                    //FrameLength: 1152
                    //MpegLayer: Layer1
                    //MpegVersion: Version1
                    //RawData: { byte[1152]}
                    //                SampleCount: 384
                    //SampleRate: 32000

                    _decompressor = new AcmMp3FrameDecompressor(waveFormat);

                    _bufferedWaveProvider = new BufferedWaveProvider(_decompressor.OutputFormat)
                    {
                        BufferDuration = TimeSpan.FromSeconds(300)
                    };
                    // ISampleProvider
                    // _bufferedWaveProvider = new SampleToWaveProvider16( );
                    //初始化输出
                    if (_waveOut == null && _bufferedWaveProvider != null)
                    {
                        _waveOut = new WaveOut();
                        _waveOut.PlaybackStopped += OnPlaybackStopped;
                        //_volumeProvider = new VolumeWaveProvider16(_bufferedWaveProvider);
                        //_waveOut.Init(_volumeProvider);
                        _waveOut.Init(_bufferedWaveProvider);
                        _waveOut.Play();
                    }


                }
                int decompressed = _decompressor.DecompressFrame(frame, _buffer, 0);
                _bufferedWaveProvider.AddSamples(_buffer, 0, decompressed);



            }
            catch (Exception ex)
            {
                // ignored
            }


        }

        public void ConIntArra(byte[] buffer)
        {
            List<int> it = new List<int>();

            string result = "";
            int i = 0;
            while (i < buffer.Length)
            {
                try
                {
                    int temp = Convert.ToInt32(buffer[i] << 8 | buffer[i + 1]);
                    it.Add(temp);
                    result += "0x" + String.Format("{0:X}", temp) + ",";

                }
                catch (Exception ex)
                {
                    string ss = "";
                }
                i += 2;
            }
            _log.Info(@"数量:" + it.Count + "  ", result);
            string s = "";
        }

        public void StreamMp3File(byte[] buffer)
        {
            try
            {


                if (IsBufferNearlyFull)
                {
                    Thread.Sleep(500);
                }
                if (_bufferedWaveProvider == null)
                {
                    WaveFormat waveFormat = new Mp3WaveFormat(
                           44100,
                              2,
                           417,
                            128000
                        );
                    _decompressor = new AcmMp3FrameDecompressor(waveFormat);
                    _bufferedWaveProvider = new BufferedWaveProvider(_decompressor.OutputFormat)
                    {
                        BufferDuration = TimeSpan.FromSeconds(300)
                    };
                    //初始化输出
                    if (_waveOut == null && _bufferedWaveProvider != null)
                    {
                        _waveOut = new WaveOut();
                        _waveOut.PlaybackStopped += OnPlaybackStopped;
                        //_volumeProvider = new VolumeWaveProvider16(_bufferedWaveProvider);
                        //_waveOut.Init(_volumeProvider);
                        _waveOut.Init(_bufferedWaveProvider);
                        _waveOut.Play();
                    }
                }
                //ConIntArra(buffer);
                //  _log.Info(@"数量:" + buffer.Length + "  ", LogInfo.GetHexLog(buffer));
                // int decompressed = _decompressor.DecompressFrame(frame, _buffer, 0);
                _bufferedWaveProvider.AddSamples(buffer, 0, buffer.Length);



            }
            catch (Exception ex)
            {
                // ignored
            }


        }
        private bool IsBufferNearlyFull
        {
            get
            {
                return _bufferedWaveProvider != null &&
                       _bufferedWaveProvider.BufferLength - _bufferedWaveProvider.BufferedBytes
                       < _bufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4;
            }
        }
        public bool Stop()
        {

            _waveOut.Stop();
            return true;
        }
        private void OnPlaybackStopped(object sender, StoppedEventArgs e)
        {
            if (e.Exception != null)
            {
                MessageBox.Show(string.Format("Playback Error {0}", e.Exception.Message));
            }
        }
    }
}
